import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import * as bodyParser from 'body-parser';
import { v4 as uuidv4 } from 'uuid';
import * as httpContext from 'express-http-context';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import { port } from './config/base';
import {serviceInfoLog} from "./common/out/logger/access.logger";
import { config } from 'dotenv';

config(); // 加载 .env 文件

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );
  function generateTraceId(): string {
    return uuidv4();
  }
  app.use(httpContext.middleware)
  // 参数解析中间件
  // Middleware to log request parameters
  app.use((req, res, next) => {
    req.trace_id = generateTraceId();
    httpContext.set('trace_id', req.trace_id);
    // Parse the request body
    // 解析请求体
    bodyParser.json()(req, res, (err) => {
      if (err) {
        console.error('trace_id:' + req.trace_id + ' Error parsing JSON:', err);
        return res.status(400).send('Invalid JSON');
      }
      console.log('trace_id:' + req.trace_id + ' Request Body:', req.body);
      serviceInfoLog(`Request URL: ${req.url};Request Params:${req.params};Request Query:${JSON.stringify(req.query)};Request Body:${JSON.stringify(req.body)};`);
    });
    next();
  });

  // 权限校验中间价
  // app.use((req, res, next) => {
  // const userInfo = new AuthService().checkAuth(req.headers);
  // if (!userInfo) {
  //   return getResponse(ERROR_CODE.VERIFY_EXPIRE, ERROR_MESSAGE[ERROR_CODE.VERIFY_EXPIRE], {})
  // }
  // next();
  // });

  app.useGlobalPipes(new ValidationPipe());

  await app.listen(port);
  console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
